import { _decorator, Button, EventTouch, Label, Node, tween, UITransform, v3 } from 'cc';
import { BasePopUp } from '../../../A-FRAME/component/ui.pop-up';
import GlobalData from '../../../game/GlobalData';
import { LocalStorageMgr } from '../../../game/LocalStorageMgr';
import { MainGameLogic } from '../../../game/MainGameLogic';
import { Popup } from '../page/popup';
import { AudioManager } from '../../../AudioManager';
import { Url } from '../../../Url';
import ServiceAPI from '../../api/service.api';
const { ccclass, property } = _decorator;

@ccclass('LotteryPage')
export class LotteryPage extends BasePopUp<typeof Popup, { type: string, value: number }> {
    protected default_return: { type: string; value: number; };
    private ui_container: UITransform;

    @property(Node)
    wardcontainer: Node = null;
    @property(Node)
    wardNodeArr: Node[] = [];
    wardTypeArr: number[] = [33, 33, 33, 33, 1, 33, 2, 33];
    @property(Node)
    lottery: Node = null;
    @property(Node)
    lottreward: Node = null;

    curAwardType: number = 0;
    curAwardNum: number = 0;
    curAwardAmount: number = 0;

    @property(Node)
    shan: Node = null;

    protected pageConfig: any = null;

    public onShow(config: any) {
        AudioManager.ins.playOneShot(Url.AUDIO.SFX9, 1);
        BasePopUp.jelly_enter(this.node);

        this.renderLocalUI()
    }
    protected initAfterOnLoad() {

    }

    private __lottery_config_cache__: ReturnType<typeof ServiceAPI.LotteryConfig>;
    async retryLotteryConfig(userId: number, retries: number = 3) {
        let attempt = 0;
        let config = null;
        while (attempt < retries) {
            try {
                config = await ServiceAPI.LotteryConfig(userId);
                if (config?.cashTotal !== undefined) {
                    this.__lottery_config_cache__ = config;
                    return config;
                } else {
                    this.__lottery_config_cache__ = config;
                    console.warn("LotteryConfig 返回空值或 cashTotal 未定义");
                }
            } catch (error) {
                console.error(`LotteryConfig 请求失败 (第 ${attempt + 1} 次):`, error);
            }
            attempt++;
            // 等待一段时间后重试（可以根据需求增加延迟）
            await new Promise(resolve => setTimeout(resolve, 1000)); // 延迟 1 秒
        }
        if (!this.__lottery_config_cache__) {
            let con = {
                lotteryResults: {
                    awardType: 3,
                    awardNum: 1,
                    awardAmount: 0,
                },
                cashTotal: GlobalData.curCashTotal
            }
            return con
        }
        return this.__lottery_config_cache__;
    }


    protected _click_event_: { [name: string]: (this: LotteryPage, button: Button) => void; } = {
        async lottBtn(btn) {
            btn.interactable = false;
            AudioManager.ins.playOneShot(Url.AUDIO.SFX4, 1);
            let config = await this.retryLotteryConfig(GlobalData.userId);
            this.pageConfig = this.getWinningAward(config);
            GlobalData.curlotteryTimes++;
            LocalStorageMgr.setItem(LocalStorageMgr.curlotteryTimes_key, GlobalData.curlotteryTimes);
            GlobalData.tempElimiTimes_lottery = 0;
            LocalStorageMgr.setItem(LocalStorageMgr.tempElimiTimes_lottery_key, GlobalData.tempElimiTimes_lottery);
            MainGameLogic.ins.updateLotteryProgress();
            this.lotteringGetWard(this.pageConfig.lotteryResults.awardType, btn);
        }
    }

    lotteringGetWard(getWardType: number, btn: Button, initialInterval: number = 0.3, speedupFactor: number = 0.9, slowdownFactor: number = 1.8) {
        const totalNodes = this.wardNodeArr.length; // 8 个节点
        let currentIndex = 0;  // 当前变色节点的下标
        let cycleCount = 0;  // 当前循环次数
        const maxCycles = 4;  // 需要循环四次
        let targetIndex = this.wardTypeArr.indexOf(getWardType); // 找到目的节点的下标
        // console.log('targetIndex', targetIndex);

        if (targetIndex === -1) {
            console.error("Invalid getWardType value.");
            return;
        }

        const highlightNode = (index: number) => {
            // 依次将当前节点的card_m子节点显示或隐藏
            for (let i = 0; i < totalNodes; i++) {
                const ward_m = this.wardNodeArr[i].getChildByName('card_m');
                ward_m.active = i === index ? true : false;
            }
        };

        const loopNodes = (interval: number, speedupFactor: number, slowdownFactor: number, onComplete: Function) => {
            const loop = () => {
                // 检查是否需要停止在目标节点
                if (cycleCount >= maxCycles && currentIndex === targetIndex) {
                    highlightNode(currentIndex); // 在判断后高亮目标节点
                    onComplete();  // 完成循环后停在目标节点
                    return;
                }

                highlightNode(currentIndex);  // 高亮当前节点

                // 增加 index
                currentIndex = (currentIndex + 1) % totalNodes;  // 更新 currentIndex

                // 如果到了第三次循环，逐渐减慢
                if (cycleCount >= 2 && currentIndex === 0) {
                    interval *= slowdownFactor;  // 第三次循环开始减速
                } else if (cycleCount < 2) {
                    // 前两次循环逐渐加速
                    interval *= speedupFactor;
                }

                // 检查循环次数
                if (currentIndex === 0) {
                    cycleCount++;
                }

                setTimeout(loop, interval * 1000);  // 按指定间隔继续循环
            };
            loop();  // 启动循环
        };

        const onComplete = () => {
            // console.log("Stopped at target node:", targetIndex);
            AudioManager.ins.stopPlayEff(Url.AUDIO.SFX10);

            btn.interactable = true;
            let config = {
                awardType: this.pageConfig.lotteryResults.awardType,
                awardAmount: this.pageConfig.lotteryResults.awardAmount,
                awardNum: this.pageConfig.lotteryResults.awardNum,
                cashTotal: this.pageConfig.cashTotal
            }
            this.scheduleOnce(() => {
                this.lottery.active = false
                this.showRewardPage(config.awardType, config.awardNum, config.awardAmount);
            }, 1)

        };

        // 执行前两次逐渐加快的循环，然后第三次逐渐减慢
        loopNodes(initialInterval, speedupFactor, slowdownFactor, onComplete);
    }

    showRewardPage(awardType, awardNum, awardAmount) {
        this.curAwardType = awardType;
        this.curAwardNum = awardNum;
        this.curAwardAmount = awardAmount;
        this.lottreward.active = true;
        BasePopUp.jelly_enter(this.lottreward);
        tween(this.shan)
            .by(6, { angle: 360 })
            .repeatForever()
            .start()
        let awardchildren = this.lottreward.getChildByName('award').children
        if (awardType == 7) {
            for (let i = 0; i < awardchildren.length; i++) {
                awardchildren[i].active = false
            }
            awardchildren[1].active = true;
            this.lottreward.getChildByName("Label").getComponent(Label).string = "x" + awardNum.toString();
        } else if (awardType == 8) {
            for (let i = 0; i < awardchildren.length; i++) {
                awardchildren[i].active = false
            }
            awardchildren[2].active = true;
            this.lottreward.getChildByName("Label").getComponent(Label).string = "x" + awardNum.toString();
        } else {
            for (let i = 0; i < awardchildren.length; i++) {
                awardchildren[i].active = false
            }
            awardchildren[0].active = true;
            this.lottreward.getChildByName('Label').getComponent(Label).string = MainGameLogic.ins.formatCashValue(awardAmount);
        }
    }

    getWinningAward(awardsConfig: Array<{ awardType: number, awardNum: number, awardAmount: number, isWinning: boolean }>) {
        return awardsConfig.find(award => award.isWinning === true);
    }

    shuffleArray<T>(array: T[]): T[] {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }

    renderLocalUI() {
        this.lottery.active = true;
        this.lottreward.active = false;

        for (let i = 0; i < this.wardNodeArr.length; i++) {
            let ward = this.wardNodeArr[i];
            ward.getChildByName('card_m').active = false
        }
    }

}

